package com.tsugun.mediaplayer.view.fragment;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.presenter.utils.SettingPreferenceHelper;
import com.tsugun.mediaplayer.view.activity.BaseActivity;
import com.tsugun.mediaplayer.view.activity.SettingActivity;

import java.lang.ref.WeakReference;

import static com.tsugun.mediaplayer.presenter.utils.LogHelper.*;

/**
 * SettingFragment
 * Created by shize on 2017/5/23.
 */

public class SettingFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener {

    private static final int MSG_SETTING = 0x23; // 消息类型
    private static final int TIME = 60; // 强制延迟时间

    private View fragment;

    private static String mClear;
    private static String mAdvise;
    private static String mAbout;

    private Context mContext;
    private Preference mPClear; // 清除缓存
    private Preference mPAdvise; // 反馈
    private Preference mPAbout; // 关于

    private SettingHandler setting = new SettingHandler(this);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragment = super.onCreateView(inflater, container, savedInstanceState);
        //        View vg = p.getView(null, container); // 可获取其中的view
//        TextView tv = (TextView) vg.findViewById(R.id.id_setting_clear);
        if (container != null) {
            mContext = container.getContext();
        }
        initData();
        bindData();
        return fragment;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mClear = getString(R.string.str_setting_other_clear);
        mAdvise = getString(R.string.str_setting_other_advise);
        mAbout = getString(R.string.str_setting_other_about);
        // 获取到了设置项
        mPClear = (Preference) getPreferenceScreen().getRootAdapter().getItem(5);
        mPAdvise = (Preference) getPreferenceScreen().getRootAdapter().getItem(6);
        mPAbout = (Preference) getPreferenceScreen().getRootAdapter().getItem(7);

    }

    /**
     * 绑定数据
     */
    private void bindData() {
        mPClear.setOnPreferenceClickListener(this);
        mPAdvise.setOnPreferenceClickListener(this);
        mPAbout.setOnPreferenceClickListener(this);
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        if (preference.getTitle().equals(mClear)) {
            Log.d(INSTANCE.getTAG(), "onPreferenceClick: 清除缓存！");
            showClearAlertDialog();
        }
        if (preference.getTitle().equals(mAdvise)) {
            Log.d(INSTANCE.getTAG(), "onPreferenceClick: 反馈！");
            startFragment(new AdviseFragment(), mAdvise);
        }
        if (preference.getTitle().equals(mAbout)) {
            Log.d(INSTANCE.getTAG(), "onPreferenceClick: 关于！");
            startFragment(new AboutFragment(), mAbout);
        }
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        setting.sendEmptyMessageDelayed(MSG_SETTING, TIME);
    }

    /**
     * 启动其他菜单界面
     */
    private void startFragment(Fragment fragment, String name) {
        SettingActivity settingActivity = (SettingActivity) mContext;
        settingActivity.startFragment(fragment, name);
    }

    /**
     * 显示清除缓存确认会话框
     */
    private void showClearAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.DeleteAlertDialog);
        AlertDialog dialog = builder.setMessage(R.string.str_setting_clear_msg)
                .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(R.string.str_clear, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        clearDiskImage();
                    }

                    /**
                     * 清除本地图片
                     */
                    private void clearDiskImage() {
                        final ProgressDialog progressDialog = new ProgressDialog(mContext, R.style.DeleteAlertDialog);
                        progressDialog.setMessage(getString(R.string.str_clearing));
                        progressDialog.show();
                        new AsyncTask<Void, Void, Short>() {
                            @Override
                            protected Short doInBackground(Void... params) {
                                SettingPreferenceHelper.INSTANCE.deleteCache(mContext);
                                try {
                                    Thread.sleep(400);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                return 1;
                            }

                            @Override
                            protected void onPostExecute(Short aShort) {
                                super.onPostExecute(aShort);
                                if (aShort == 1) {
                                    Snackbar.make(fragment, getString(R.string.str_setting_clear_complete),
                                            Snackbar.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                }
                            }
                        }.execute();
                    }
                }).create();
        dialog.show();
    }

    /**
     * 应用设置参数
     */
    public void onSettingChanged() {
        ((BaseActivity) getActivity()).onSettingChanged();
    }

    /**
     * 强制延迟更新设置参数
     */
    private static class SettingHandler extends Handler {
        private WeakReference<SettingFragment> wp;

        SettingHandler(SettingFragment p) {
            wp = new WeakReference<>(p);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SettingFragment p = wp.get();
            if (msg.what == MSG_SETTING) {
                p.onSettingChanged();
            }
        }
    }
}
